package main

import (
	"bytes"
	"fmt"
	"github.com/zhan3333/glog"
	"net/http"
	"os/exec"
	"server/src/logging"
	"server/src/storage"
	"strconv"
)

var cfg *Config

func main() {
	var err error

	storage.Init(storage.RootPath())
	// 启动日志
	logging.DisableBootScreenLog()
	logging.LogBoot()

	cfg, err = loadConfig("")
	if err != nil {
		glog.Channel("parsedatad").Infof("读配置文件失败:%s", err.Error())
		return
	}

	http.HandleFunc("/parse", parse)

	http.HandleFunc("/checksum", checkSum)

	glog.Channel("parsedatad").Infof("开始监听端口:%s %s %t", cfg.HttpPort, " HTTPS:", cfg.HTTPS)
	if cfg.HTTPS {
		err = http.ListenAndServeTLS(cfg.HttpPort, cfg.CertFile, cfg.KeyFile, nil)
	} else {
		err = http.ListenAndServe(cfg.HttpPort, nil)
	}
	if err != nil {
		glog.Channel("parsedatad").Infof("监听端口:%s %s %s", cfg.HttpPort, "失败:", err.Error())
	}

}

func parse(w http.ResponseWriter, req *http.Request) {
	w.Header().Add("Access-Control-Allow-Origin", "*")
	glog.Channel("parsedatad").Infof("parse start......")
	req.ParseForm()
	text := req.FormValue("text")
	text = execparse(text)
	w.Write([]byte(text))
}

func execparse(text string) string {

	cmd := exec.Command(cfg.ParseFile, text)
	var bufStdout bytes.Buffer
	cmd.Stdout = &bufStdout
	cmd.Stderr = &bufStdout

	err := cmd.Run()
	if err != nil {
		return err.Error()
	}
	return string(bufStdout.Bytes())
}

func checkSum(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	glog.Channel("parsedatad").Infof("checkSum start......")
	str := req.FormValue("str")
	if str == "" {
		w.Write([]byte("请输入要计算的数据"))
		return
	}
	iLen := len(str)
	if iLen%2 != 0 {
		w.Write([]byte("字符串长度必须为双数，请重新输入"))
		return
	}

	sum := 0
	sTemp := ""
	for i := 0; i < iLen; i += 2 {
		sTemp = str[i : i+2]
		sum += str2Hex(sTemp)
	}

	sTemp = fmt.Sprintf("%X", sum)
	iLen = len(sTemp)
	if iLen > 2 {
		sTemp = sTemp[iLen-2:]
	}
	w.Write([]byte(sTemp))
}

func str2Hex(str string) int {
	if str == "" {
		return 0
	}
	i, err := strconv.ParseInt(str, 16, 0)
	if err != nil {
		return 0
	} else {
		return int(i)
	}
}
